﻿using AutoMapper;
using B.S.BasicData.API.Read.Application.Command.User;
using B.S.BasicData.API.Read.DTOS.UserRoleMenu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;
using System.Collections.Generic;

namespace B.S.BasicData.API.Read.Application.Handler.User
{
    /// <summary>
    /// 获取用户信息请求命令处理类
    /// </summary>
    public class GetUserHandler : IRequestHandler<GetUserCommand, ApiResult<List<UserDTO>>>
    {
        IBaseRepository<UserModel> userRep;
        IBaseRepository<RoleModel> roleRep;
        IBaseRepository<UserRoleModel> userRoleRep;
        IMapper mapper;

        public GetUserHandler(IBaseRepository<UserModel> userRep, IBaseRepository<RoleModel> roleRep, IBaseRepository<UserRoleModel> userRoleRep, IMapper mapper)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.userRoleRep = userRoleRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<UserDTO>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<UserDTO>> res = new ApiResult<List<UserDTO>>();

                var users = userRep.GetAll().OrderByDescending(x=>x.Id).Where(x => x.IsDeleted == false);

               
                //将数据通过AutoMapper映射到UsersRoleDTO中
                IList<UserDTO> userDTO = mapper.Map<IList<UserDTO>>(users);
                foreach (var item in userDTO)
                {
                    //根据用户编号获取满足条件的用户角色信息
                    var userroleinfo = userRoleRep.GetAll().Where(x => x.IsDeleted == false && x.UserId==item.Id);
                    //获取所有角色信息
                    var roleinfo = roleRep.GetAll().Where(x => x.IsDeleted == false);

                    //通过Ling关联用户、角色
                    var query = (from a in userroleinfo
                                 join b in roleinfo on a.RoleId equals b.Id
                                 select new { a, b }).ToList();

                    //从数据集中单独获取角色名称信息
                    List<string> roleName = query.Select(x => x.b.RoleName).ToList();

                    //Join()为字符串连接方法  参数1代表分隔符 参数2代表需要操作的数组
                    item.RoleName = string.Join(",", roleName);
                }

                
                
                res.Msg = "获取用户信息";
                res.Code = ApiEnum.Success;
                res.Data = userDTO.ToList();
                return Task.FromResult(res);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
